from flask import g, jsonify
from flask_httpauth import HTTPBasicAuth
from . import api
from .errors import unauthorized, forbidden
from ..models import User, AnonymousUser
from .. import db

auth = HTTPBasicAuth()

# 授权进行的验证
@auth.verify_password
def verify_password(user_id, password):
    print('[A] api: verify password')
    # print('[*] user_id: ' + user_id)

    if user_id == '':
        print('[-] user_id == null')
        g.current_user = AnonymousUser()
        return True

    user = User.query.get(user_id)
    if user:
        print('[+] user: %r login' % user.nickName)
        g.current_user = user
        return True

    return False


# 授权失败返回的错误
@auth.error_handler
def auth_error():
    return unauthorized('Invaild credentials')


@api.before_request
@auth.login_required
def before_request():
    # print('[A] api: before request')
    if g.current_user.is_anonymous:
        return forbidden('Anonymous Account')


# 请求完毕之后，断开数据库连接！非常重要！！！
@api.teardown_request
def shutdown_session(exception=None):
    # print('remove session')
    db.session.remove()